// pages/adoption-list/adoption-list.js
const app = getApp();
const util = require('../../utils/util.js');

Page({
  data: {
    searchKeyword: '',
    petType: '',
    petGender: '',
    publisher: '',
    adoptionList: [],
    currentPage: 1,
    pageSize: 10,
    hasMore: true
  },

  onLoad() {
    this.loadAdoptionPosts();
  },

  onShow() {
    // 从编辑页返回时刷新列表
    if (this.data.adoptionList.length > 0) {
      this.setData({
        currentPage: 1
      });
      this.loadAdoptionPosts();
    }
  },

  // 加载领养帖子
  loadAdoptionPosts(isLoadMore = false) {
    if (!isLoadMore) {
      app.showLoading();
    }

    const userInfo = wx.getStorageSync('userInfo');
    const params = {
      page: this.data.currentPage,
      size: this.data.pageSize,
      currentUserId: userInfo ? userInfo.id : null
    };

    if (this.data.searchKeyword) {
      params.breed = this.data.searchKeyword;
    }
    if (this.data.petType) {
      params.petType = this.data.petType;
    }
    if (this.data.petGender) {
      params.petGender = this.data.petGender;
    }
    if (this.data.publisher) {
      params.publisher = this.data.publisher;
    }

    app.request({
      url: '/adoption/user/list',
      method: 'GET',
      data: params
    }).then(res => {
      if (res.success) {
        const posts = (res.data.records || []).map(item => ({
          id: item.id,
          title: item.title,
          petType: item.petType || '',
          petGender: item.petGender || '',
          breed: item.breed || '',
          petName: item.petName || '',
          location: item.location || '',
          status: item.status || '',
          userNickname: item.userNickname || '匿名用户',
          userAvatar: item.userAvatar || 'https://img1.baidu.com/it/u=1537776144,3012351076&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500',
          image: this.getFirstImage(item.photos),
          isMyPost: userInfo && item.userId === userInfo.id,
          createTime: util.formatDateTime(item.createTime)
        }));

        if (isLoadMore) {
          this.setData({
            adoptionList: this.data.adoptionList.concat(posts),
            hasMore: posts.length >= this.data.pageSize
          });
        } else {
          this.setData({
            adoptionList: posts,
            hasMore: posts.length >= this.data.pageSize
          });
        }
      }
    }).catch(err => {
      app.showToast('加载失败，请稍后重试');
      console.error('加载领养帖子失败', err);
    }).finally(() => {
      app.hideLoading();
    });
  },

  // 获取第一张图片
  getFirstImage(photos) {
    if (!photos) {
      return 'https://img1.baidu.com/it/u=2531584226,2194794184&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500';
    }
    const imageArray = photos.split(',');
    return imageArray[0] || 'https://img1.baidu.com/it/u=2531584226,2194794184&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500';
  },

  // 搜索输入
  onSearchInput(e) {
    this.setData({
      searchKeyword: e.detail.value
    });
  },

  // 搜索
  handleSearch() {
    this.setData({
      currentPage: 1
    });
    this.loadAdoptionPosts();
  },

  // 按宠物类型筛选
  filterByPetType(e) {
    const type = e.currentTarget.dataset.type;
    this.setData({
      petType: type,
      currentPage: 1
    });
    this.loadAdoptionPosts();
  },

  // 按性别筛选
  filterByGender(e) {
    const gender = e.currentTarget.dataset.gender;
    this.setData({
      petGender: gender,
      currentPage: 1
    });
    this.loadAdoptionPosts();
  },

  // 按发布者筛选
  filterByPublisher(e) {
    const publisher = e.currentTarget.dataset.publisher;
    this.setData({
      publisher: publisher,
      currentPage: 1
    });
    this.loadAdoptionPosts();
  },

  // 加载更多
  loadMore() {
    if (!this.data.hasMore) return;
    
    this.setData({
      currentPage: this.data.currentPage + 1
    });
    this.loadAdoptionPosts(true);
  },

  // 查看详情
  viewDetail(e) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/adoption-detail/adoption-detail?id=${id}`
    });
  },

  // 显示发布弹窗
  showPublishDialog() {
    const userInfo = wx.getStorageSync('userInfo');
    if (!userInfo) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      setTimeout(() => {
        wx.navigateTo({
          url: '/pages/login/login'
        });
      }, 1500);
      return;
    }

    wx.navigateTo({
      url: '/pages/adoption-publish/adoption-publish'
    });
  },

  // 编辑帖子
  editPost(e) {
    const item = e.currentTarget.dataset.item;
    // 跳转到编辑页面，传递帖子数据
    wx.navigateTo({
      url: `/pages/adoption-publish/adoption-publish?id=${item.id}&mode=edit`
    });
  }
});


